package com.ecjtu.stadiumre_servations.service.impl;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.ecjtu.stadiumre_servations.config.AlipayConfig;
import com.ecjtu.stadiumre_servations.service.AlipayService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.Map;
@Service
public class AlipayServiceImpl implements AlipayService {

    private  final Logger logger = LoggerFactory.getLogger(AlipayServiceImpl.class);

    @Override
    public String toAlipay(Map<String, String> sourceMap) throws IOException {
        // 1. 创建AlipayClient实例，连接支付宝开放平台
        AlipayClient alipayClient = new DefaultAlipayClient(
                AlipayConfig.URL,
                AlipayConfig.APPID,
                AlipayConfig.RSA_PRIVATE_KEY,
                AlipayConfig.FORMAT,
                AlipayConfig.CHARSET,
                AlipayConfig.ALIPAY_PUBLIC_KEY,
                AlipayConfig.SIGNTYPE
        );

        // 2. 创建支付请求对象并设置回调URL
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url);  // 支付成功后跳转的页面
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);  // 支付宝异步通知URL

        // 3. 构建支付业务模型
        AlipayTradeWapPayModel model = new AlipayTradeWapPayModel();
        model.setOutTradeNo(sourceMap.get("out_trade_no"));      // 商户订单号
        model.setProductCode("FAST_INSTANT_TRADE_PAY");          // 产品码（固定值）
        model.setTotalAmount(sourceMap.get("total_amount"));    // 支付金额
        model.setSubject(sourceMap.get("order_name"));          // 订单标题
        model.setBody(URLDecoder.decode(sourceMap.get("body"), "UTF-8"));  // 订单描述（解码处理）
        alipayRequest.setBizModel(model);

        // 4. 执行请求并获取HTML表单
        String form = "";
        try {
            form = alipayClient.pageExecute(alipayRequest).getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return form;
    }


    @Override
    public String refund(Map<String, String> refundParams) throws IOException, AlipayApiException {
        // 1. 创建AlipayClient实例
        AlipayClient alipayClient = new DefaultAlipayClient(
                AlipayConfig.URL,
                AlipayConfig.APPID,
                AlipayConfig.RSA_PRIVATE_KEY,
                AlipayConfig.FORMAT,
                AlipayConfig.CHARSET,
                AlipayConfig.ALIPAY_PUBLIC_KEY,
                AlipayConfig.SIGNTYPE
        );

        // 2. 创建退款请求对象
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();

        // 3. 设置退款业务参数（拼接JSON字符串）
        request.setBizContent("{" +
                "\"out_trade_no\":\"" + refundParams.get("out_trade_no") + "\"," +
                "\"refund_amount\":\"" + refundParams.get("refund_amount") + "\"" +
                "}");

        // 4. 执行退款请求并处理响应
        AlipayTradeRefundResponse response = alipayClient.execute(request);
        if (response.isSuccess()) {
            return "退款成功";
        } else {
            return "退款失败：" + response.getMsg();
        }
    }

}